<template>
  <div class="login">
    <div class="login_box">
      <div class="flex-box back">
        <a href="javascript:void(0);" @click="goBack">{{ $t('login.back') }}</a>
      </div>
      <div class="flex-box language">
        <el-select size="small" v-model="language" :placeholder="$t('text.pleaseSelect')" @change="setLanguage">
          <template #prefix>
            <img src="@/assets/en.png" class="lang-icon-s" alt="" v-if="language === 'en'" />
            <img src="@/assets/zh-cn.png" class="lang-icon-s" alt="" v-if="language === 'zh-cn'" />
          </template>
          <el-option v-for="item in languages" :key="item.value" :label="item.label" :value="item.value">
            <div class="lang-item">
              <img src="@/assets/en.png" class="lang-icon" alt="" v-if="item.value === 'en'" />
              <img src="@/assets/zh-cn.png" class="lang-icon" alt="" v-if="item.value === 'zh-cn'" />
              <span>{{ item.label }}</span>
            </div>
          </el-option>
        </el-select>
      </div>
      <div class="login_box_l">
        <template v-if="locale == 'en'">
          <LoginEn />
        </template>
        <template v-else-if="locale == 'zh-cn'">
          <LoginZhcn />
        </template>
      </div>
      <div class="login_box_inner">
        <div class="login_logo" style="margin-top: 34px">
          <h2>
            <span>{{ $t('button.register') }}</span>
          </h2>
          <span class="login_tag"><span>{{ $t('login.tag') }}</span><strong>2G</strong></span>
        </div>
        <div class="login-main">
          <div class="login_main_inner" v-loading="formData.loading">
            <div class="login_item login_user">
              <input v-model.trim="formData.email" type="text" name="email" :placeholder="$t('input.email')" />
            </div>
            <div class="login_item login_pwd">
              <input v-model.trim="formData.password" type="password" name="password" :placeholder="$t('input.password')" />
            </div>
            <div class="login_item login_pwd">
              <input
                v-model.trim="formData.password_confirmation"
                type="password"
                name="password"
                :placeholder="$t('input.passwordConfirmation')"
              />
            </div>
            <div class="login_item input_code clearfix">
              <div class="input_code">
                <input v-model.trim="formData.invite_code" type="text" name="invite_code" :placeholder="$t('input.invitationCode')" />
              </div>
            </div>
            <div class="login_item login_captcha clearfix">
              <div class="input_captcha">
                <input v-model.trim="formData.email_code" type="text" name="email_code" :placeholder="$t('input.emailVerificationCode')" />
                <div v-if="!mailCodeData.send" class="get_captcha" @click="getCode">
                  <a href="javascript:java(0);">
                    <span>{{ !mailCodeData.loading ? $t('login.getVerificationCode') : $t('button.sending') }}</span>
                  </a>
                </div>
                <div v-else  class="get_captcha">
                  <a href="javascript:java(0);">
                    <el-countdown ref="countdownRef" @finish="onFinished" format="mm:ss" :value="mailCodeData.time" time-indices :value-style="{ 'color': '#0097fc' }" />
                  </a>
                </div>
              </div>
            </div>
            <div class="login_item privacy">
              <p>
                <a :href="$t('link.userServiceAgreement')" target="_blank">{{ $t('login.userServiceAgreement') }}</a>
                <span>{{ $t('login.and') }}</span>
                <a :href="$t('link.privacypolicy')" target="_blank">{{ $t('login.privacypolicy') }}</a>
              </p>
            </div>
            <div class="login_item login_bar">
              <a href="javascript:void(0);" @click="onSubmit">
                <span>{{ $t('button.register') }}</span>
              </a>
            </div>
            <div class="reg-tips" style="margin-bottom: 10px">
              <p>
                <span>{{ $t('login.haveAccount') }}</span>
                <a href="javascript:void(0);" @click="toLogin">{{ $t('login.goToLogin') }}</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="LoginPage">
  import { useRoute, useRouter } from 'vue-router';
  import { ref, reactive, onMounted } from 'vue';
  import { useUserStore } from '@/store/modules/user';
  import { sendMailCodeApi } from '@/api/index';
  import { useI18n } from 'vue-i18n';
  import { setLang } from '@/i18n';
  import LoginEn from '../components/login/en.vue';
  import LoginZhcn from '../components/login/zh-cn.vue';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const language = ref('en');
  const languages = ref([
    {
      value: 'en',
      label: 'English',
    },
    {
      value: 'zh-cn',
      label: '简体中文',
    },
  ]);

  const formData = reactive({
    email: '',
    password: '',
    password_confirmation: '',
    email_code: '',
    invite_code: '',
    channel_key: sessionStorage.getItem('channel_key') || '',
    channel_value: sessionStorage.getItem('channel_value') || '',
    loading: false,
  });

  const mailCodeData = reactive({
    key: '',
    image: '',
    time: 0,
    loading: false,
    send: false,
  });

  const setLanguage = (lang) => {
    setLang(lang);
  };

  const countdownRef = ref();

  const toCenter = () => {
    router.push({
      path: '/center',
      query: {
        t: new Date().getTime(),
      },
    });
  };

  const toLogin = () => {
    router.push({
      path: '/user/login',
      query: {
        t: new Date().getTime(),
      },
    });
  };

  const goBack = () => {
    if (locale.value == 'en') {
      window.location.href = 'https://ipxproxy.com/';
    } else if (locale.value == 'zh-cn') {
      window.location.href = 'https://zh.ipxproxy.com/';
    }
  };

  const getCode = async () => {
    if (!formData.email) {
      ElMessage.error('The email field is required');
      return false;
    }
    if (mailCodeData.loading) return false;
    mailCodeData.loading = true;
    mailCodeData.send = false;
    sendMailCodeApi({
      email: formData.email.trim(),
    })
      .then((res) => {
        mailCodeData.loading = false;
        mailCodeData.send = true;
        mailCodeData.time = Date.now() + 1000 * 60 * 5;
        ElMessage.success(res.message);
      })
      .catch((err) => {
        mailCodeData.loading = false;
        mailCodeData.send = false;
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onSubmit = async () => {
    if (!formData.email) {
      ElMessage.error('The email field is required');
      return false;
    }
    if (!formData.password) {
      ElMessage.error('The password field is required');
      return false;
    }
    if (!formData.password_confirmation) {
      ElMessage.error('The password confirmation field is required');
      return false;
    }
    if (!(formData.password == formData.password_confirmation)) {
      ElMessage.error('The password confirmation does not match.');
      return false;
    }
    if (!formData.email_code) {
      ElMessage.error('The captcha field is required.');
      return false;
    }
    if (formData.loading) return false;
    formData.loading = true;
    await userStore
      .register({
        ...formData,
      })
      .then((res) => {
        if (res && res.token) {
          toCenter(res.token);
        }
        formData.loading = false;
      });
  };

  const onFinished = () => {
    mailCodeData.send = false;
    mailCodeData.time = 0;
  };

  onMounted(async () => {
    language.value = sessionStorage.getItem('lang') || 'en';
    formData.invite_code = sessionStorage.getItem('channel_key') == 'hz' ? sessionStorage.getItem('channel_value') : '';
  });
</script>

<style scoped lang="scss">
  .login {
    padding: 20px;

    h2 {
      text-align: center;
    }

    .nut-form-item {
      margin-bottom: 20px;
      border-radius: 20px;
      background: #f2f3f5;

      input {
        background: transparent;
      }
    }
  }
</style>
